package com.yc.base;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONTokener;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Objects;

/**
 * @author BAO
 * @since 2020/9/6 10:22
 */
@Slf4j
public class BaseController {

    /**
     * 获取当前请求
     *
     * @return request
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取当前请求
     *
     * @return response
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    @SneakyThrows
    public JSONObject getParams() {
        HttpServletRequest request = getRequest();
        String methodName = request.getMethod();
        if (methodName.equals("GET")) {
            return getParameter(request);
        } else if (methodName.equals("POST")) {
            String contentType = request.getContentType();
            if (StrUtil.isEmpty(contentType)) {
                throw new Exception("无效的content-type");
            }
            if (contentType.contains("application/json")) {
                request.setCharacterEncoding("utf-8");
                InputStream is = request.getInputStream();
                try {
                    return new JSONObject(new JSONTokener(is, JSONConfig.create()));
                } catch (Exception ex) {
                    throw new Exception("参数无效");
                }
            } else if (contentType.contains("application/x-www-form-urlencoded")) {
                return getParameter(request);
            } else {
                throw new Exception("无效的content-type");
            }
        }
        throw new Exception("参数无效");
    }

    private JSONObject getParameter(HttpServletRequest request) {
        Enumeration<String> names = request.getParameterNames();
        JSONObject jsonObject = new JSONObject();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            jsonObject.putOpt(name, value);
        }
        return jsonObject;
    }
}
